package cn.dinkevin.xui.widget.listview.swipe_menu;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;

/**
 * 可调整高度的 ListView
 * Created by ChengPengFei on 2017/2/23 0023.</br>
 * Copyright ©2017 juziwl, All Rights Reserved.
 */

public class AutoHeightSwipeMenuListView extends SwipeMenuListView{

    public AutoHeightSwipeMenuListView(Context context) {
        super(context);
    }

    public AutoHeightSwipeMenuListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public AutoHeightSwipeMenuListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * 自动计算调整 ListView 高度
     */
    public void autoHeight(){
        ListAdapter adapter = getAdapter();
        ViewGroup.LayoutParams params = getLayoutParams();

        if(adapter == null){
            params.height = 0;
            setLayoutParams(params);
            return;
        }

        int totalHeight = getDividerHeight() * (adapter.getCount() - 1);
        for (int i = 0; i < adapter.getCount(); i++) {
            View listItem = adapter.getView(i, null, this);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        params.height = totalHeight;
        setLayoutParams(params);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = View.MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, View.MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }
}
